package com.nmgydy.admin.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.nmgydy.beans.ListBean;
import com.nmgydy.beans.ResultBean;
import com.nmgydy.model.UserConfirm;
import com.nmgydy.util.Functions;
import com.nmgydy.util.HibernateDao;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

@Controller
@RequestMapping("/admin/userConfirm")
public class UserConfirmController {

	@Resource
	private HibernateDao hibernateDao;

	@RequestMapping(value = "list", method = RequestMethod.GET)
	public String list(HttpServletRequest request, HttpServletResponse response, Model model) {
		return "/admin/userConfirm/list";
	}

	@RequestMapping(value = "add", method = RequestMethod.GET)
	public String add() {
		return "/admin/userConfirm/add";
	}

	@RequestMapping(value = "edit", method = RequestMethod.GET)
	public String edit(HttpServletRequest request, HttpServletResponse response, Model model) {
		return "/admin/userConfirm/edit";
	}
	
	@RequestMapping(value = "search", method = RequestMethod.GET)
	public String search(HttpServletRequest request, HttpServletResponse response, Model model) {
		return "/admin/userConfirm/search";
	}
	@RequestMapping(value = "event_item_list", method = RequestMethod.GET)
	public String eventItemList(HttpServletRequest request, HttpServletResponse response, Model model) {
		return "/admin/userConfirm/event_item_list";
	}
	@RequestMapping(value = "listData", method = RequestMethod.POST)
	@ResponseBody
	public String listData(HttpServletRequest request, HttpServletResponse response, Model model) {
		String pageSize = request.getParameter("pageSize");
		String pageIndex = request.getParameter("pageIndex");
		String sortField = request.getParameter("sortField");
		String sortOrder = request.getParameter("sortOrder");

		String hql = "from UserConfirm a where a.id=a.id ";
		Map<String, Object> params = new HashMap<String, Object>();
		
		String userId = request.getParameter("userId");
		if (!Functions.isEmpty(userId)) {
			hql += " and userId like :userId";
			params.put("userId", userId);
		}
		String userName = request.getParameter("userName");
		if (!Functions.isEmpty(userName)) {
			hql += " and userName like :userName";
			params.put("userName", "%" + userName + "%");
		}
		String phoneNumber = request.getParameter("phoneNumber");
		if (!Functions.isEmpty(phoneNumber)) {
			hql += " and phoneNumber like :phoneNumber";
			params.put("phoneNumber", "%" + phoneNumber + "%");
		}
		String eventItemId = request.getParameter("eventItemId");
		if (!Functions.isEmpty(eventItemId)) {
			hql += " and eventItemId like :eventItemId";
			params.put("eventItemId", eventItemId);
		}
		String title = request.getParameter("title");
		if (!Functions.isEmpty(title)) {
			hql += " and title like :title";
			params.put("title", "%" + title + "%");
		}
		String lipic = request.getParameter("lipic");
		if (!Functions.isEmpty(lipic)) {
			hql += " and lipic like :lipic";
			params.put("lipic", "%" + lipic + "%");
		}
		String startTime = request.getParameter("startTime");
		if (!Functions.isEmpty(startTime)) {
			hql += " and startTime like :startTime";
			params.put("startTime", "%" + startTime + "%");
		}
		String address = request.getParameter("address");
		if (!Functions.isEmpty(address)) {
			hql += " and address like :address";
			params.put("address", "%" + address + "%");
		}
		String createTime = request.getParameter("createTime");
		if (!Functions.isEmpty(createTime)) {
			hql += " and createTime like :createTime";
			params.put("createTime", "%" + createTime + "%");
		}
		String status = request.getParameter("status");
		if (!Functions.isEmpty(status)) {
			hql += " and status like :status";
			params.put("status", "%" + status + "%");
		}
		Boolean sorted = !(sortField == null || "".equals(sortField) || sortOrder == null || "".equals(sortOrder));
		if (sorted) {
			hql += " order by :sortField :sortOrder";
			params.put("sortField", sortField);
			params.put("sortOrder", sortOrder);
		}else{
			hql += " order by id desc";
		}
		
		Boolean paged = !(pageSize == null || "".equals(pageSize) || pageIndex == null || "".equals(pageIndex));
		if (paged) {
			long total = hibernateDao.count(hql, params);
			List<?> list = hibernateDao.list(hql, params, Integer.parseInt(pageIndex) + 1, Integer.parseInt(pageSize));
			return JSON.toJSONString(new ListBean(list,total));
		} else {
			long total = hibernateDao.count(hql, params);
			List<?> list = hibernateDao.list(hql, params);
			return JSON.toJSONString(new ListBean(list,total));
		}
	}
	@RequestMapping(value = "eventItemListData", method = RequestMethod.POST)
	@ResponseBody
	public String eventItemListData(HttpServletRequest request, HttpServletResponse response, Model model) {
		String pageSize = request.getParameter("pageSize");
		String pageIndex = request.getParameter("pageIndex");
		String sortField = request.getParameter("sortField");
		String sortOrder = request.getParameter("sortOrder");

		String hql = "from EventItem a where a.id=a.id ";
		Map<String, Object> params = new HashMap<String, Object>();


		Boolean sorted = !(sortField == null || "".equals(sortField) || sortOrder == null || "".equals(sortOrder));
		if (sorted) {
			hql += " order by :sortField :sortOrder";
			params.put("sortField", sortField);
			params.put("sortOrder", sortOrder);
		}else{
			hql += " order by id desc";
		}

		if (!Functions.isEmpty(pageIndex) && !Functions.isEmpty(pageSize)) {
			long total = hibernateDao.count(hql, params);
			List<?> list = hibernateDao.list(hql, params, Integer.parseInt(pageIndex) + 1, Integer.parseInt(pageSize));
			return JSON.toJSONString(new ListBean(list,total));
		} else {
			long total = hibernateDao.count(hql, params);
			List<?> list = hibernateDao.list(hql, params);
			return JSON.toJSONString(new ListBean(list,total));
		}
	}

	//添加报名清单
	@RequestMapping(value = "save", method = RequestMethod.POST)
	@ResponseBody
	public String save(UserConfirm userConfirm,HttpServletRequest request, HttpServletResponse response, Model model) {

		if(userConfirm.getUserId() == null){
			return JSON.toJSONString(ResultBean.failure("用户ID不能为空"));
		}
		if(Functions.isEmpty(userConfirm.getUserName())){
			return JSON.toJSONString(ResultBean.failure("用户姓名不能为空"));
		}
		if(Functions.isEmpty(userConfirm.getPhoneNumber())){
			return JSON.toJSONString(ResultBean.failure("手机号不能为空"));
		}
		if(userConfirm.getEventItemId() == null){
			return JSON.toJSONString(ResultBean.failure("展览ID不能为空"));
		}
		if(Functions.isEmpty(userConfirm.getTitle())){
			return JSON.toJSONString(ResultBean.failure("展览标题不能为空"));
		}
		if(Functions.isEmpty(userConfirm.getLipic())){
			return JSON.toJSONString(ResultBean.failure("图片不能为空"));
		}
		if(Functions.isEmpty(userConfirm.getStartTime())){
			return JSON.toJSONString(ResultBean.failure("开始时间不能为空"));
		}
		if(Functions.isEmpty(userConfirm.getAddress())){
			return JSON.toJSONString(ResultBean.failure("展览地址不能为空"));
		}
		if(Functions.isEmpty(userConfirm.getCreateTime())){
			return JSON.toJSONString(ResultBean.failure("创建时间不能为空"));
		}
		if(Functions.isEmpty(userConfirm.getStatus())){
			return JSON.toJSONString(ResultBean.failure("参加状态不能为空"));
		}

		boolean flag = hibernateDao.save(userConfirm);
		if(flag){
			return JSON.toJSONString(ResultBean.success("报名清单添加成功"));
		}
		return JSON.toJSONString(ResultBean.failure("报名清单添加失败"));
		
	}
	
	//编辑报名清单
	@RequestMapping(value = "update", method = RequestMethod.POST)
	@ResponseBody
	public String update(UserConfirm userConfirm,HttpServletRequest request, HttpServletResponse response, Model model) {

		if(userConfirm.getUserId() == null){
			return JSON.toJSONString(ResultBean.failure("用户ID不能为空"));
		}
		if(Functions.isEmpty(userConfirm.getUserName())){
			return JSON.toJSONString(ResultBean.failure("用户姓名不能为空"));
		}
		if(Functions.isEmpty(userConfirm.getPhoneNumber())){
			return JSON.toJSONString(ResultBean.failure("手机号不能为空"));
		}
		if(userConfirm.getEventItemId() == null){
			return JSON.toJSONString(ResultBean.failure("展览ID不能为空"));
		}
		if(Functions.isEmpty(userConfirm.getTitle())){
			return JSON.toJSONString(ResultBean.failure("展览标题不能为空"));
		}
		if(Functions.isEmpty(userConfirm.getLipic())){
			return JSON.toJSONString(ResultBean.failure("图片不能为空"));
		}
		if(Functions.isEmpty(userConfirm.getStartTime())){
			return JSON.toJSONString(ResultBean.failure("开始时间不能为空"));
		}
		if(Functions.isEmpty(userConfirm.getAddress())){
			return JSON.toJSONString(ResultBean.failure("展览地址不能为空"));
		}
		if(Functions.isEmpty(userConfirm.getCreateTime())){
			return JSON.toJSONString(ResultBean.failure("创建时间不能为空"));
		}
		if(Functions.isEmpty(userConfirm.getStatus())){
			return JSON.toJSONString(ResultBean.failure("参加状态不能为空"));
		}

		boolean flag = hibernateDao.update(userConfirm);
		if(flag){
			return JSON.toJSONString(ResultBean.success("报名清单更新成功"));
		}
		return JSON.toJSONString(ResultBean.failure("报名清单更新失败"));
	}
	
	//删除报名清单
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(HttpServletRequest request, HttpServletResponse response, Model model) {
		String ids = request.getParameter("ids");
		if (ids != null && !"".equals(ids)) {
			ids = ids.replace("'", "");
		} else {
			return JSON.toJSONString(ResultBean.failure("ID集合信息不存在!"));
		}
		String[] idStrs = ids.split(",");
		if(idStrs.length <= 0){
			return JSON.toJSONString(ResultBean.failure("请正确选择记录!"));
		}
		List<Long> delIdList = new ArrayList<Long>(idStrs.length);
		for(String id:idStrs){
			delIdList.add(Long.parseLong(id));
		}
		Session session = null;
		Transaction transaction = null;
		try{
			session = hibernateDao.getSessionFactory().openSession();
			transaction = session.beginTransaction();
			String deleteHql = "delete from UserConfirm where id in (:ids)";
			int row = session.createQuery(deleteHql).setParameterList("ids", delIdList).executeUpdate();
			transaction.commit();
			System.out.println("删除报名清单信息成功 -- 受影响行数：" + row);
			return JSON.toJSONString(ResultBean.failure("删除成功，删除成功条数" + row + "条。!"));
		} catch (Exception e) {
			e.printStackTrace();
			if (transaction != null) {
				transaction.rollback();
			}
			return JSON.toJSONString(ResultBean.failure("删除失败!"));
		} finally {
			session.close();
		}
	}

}
